from bottle import route, run, static_file, request, BaseRequest, template, response
import bottle
import json
import time

def allow_cross_domain(fn):
    def _enable_cors(*args, **kwargs):
        #set cross headers
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'GET,POST,PUT,OPTIONS'
        allow_headers = 'Referer, Accept, Origin, User-Agent'
        response.headers['Access-Control-Allow-Headers'] = allow_headers     
        if bottle.request.method != 'OPTIONS':
            # actual request; reply with the actual response
            return fn(*args, **kwargs)    
    return _enable_cors

@route('/user')
def user() :
    print(dict(request.headers))
    return {'name':'Tom', 'age':12}

@route('/ping')
def ping() :
    print(dict(request.headers))
    return 'pong'

@route('/')
def root() :
    print(dict(request.headers))
    return 'Welcome to bottle!!!'

@route('/list')
@allow_cross_domain
def list() :
    print(dict(request.headers))
    return json.dumps(['Tom', 'Jenny', 'Jim'])

@route('/post', method='POST')
def post() :
    print(dict(request.headers))
    for s in request.body:
        print(s)
    return 'post success!!!'   


@route('/put', method='PUT')
def put() :
    print(dict(request.headers))
    for s in request.body:
        print(s)
    return 'put success!!!'  

print('start server...')
run(host="127.0.0.1", port=8080)